import axios from "axios"
import router from '../router'

import ElementUI from "element-ui"

import NProgress from "nprogress"

axios.defaults.baseURL = process.env.NODE_ENV==='development' ?'/api':'http://www.chst.vip'

axios.defaults.witchCredentials = true; //允许请求认证

//创建拦截器,可以给每个请求都携带上想要传递的内容
//config就是传输的请求
axios.interceptors.request.use(config=>{    
    // 判断登录和注册是不需要token
    if(config.url == "users/login"){
        return config
    }else{
        let token = localStorage.getItem('stu-token')
    config.headers['authorization'] = token;
    // console.log(config);
    //放行
    return config
    }
})

//响应拦截
axios.interceptors.response.use(config=>{
    // console.log(config);
    let {data} = config;
    if(data.code == "1004" || data.code == "10022"){
        //在当前api中由后端定义的1004错误码代表token校验失败,页面提示错误并且让页面跳转到登录页
        ElementUI.Message.error("登录信息失效请重新登录")
        localStorage.removeItem("stu-token")
        router.push('/login')
        window.location.reload()

    }
    return config
})

axios.create({

    timeout:40000
})

export default axios